/**
 * Created by Administrator on 2016/6/21.
 */
import React from 'react';

class TodoInput extends React.Component{
  add(e){
    if(e.keyCode != 13) return;
    var text = this.refs.input.value;
    if(text == '') return;
    this.props.onAdd(text);
    e.target.value = ''
  }

  render() {
    return (
      <input type="text" className="todo-input" placeholder="To do something..." onKeyDown={this.add.bind(this)} ref="input" />
    );
  }
}

class TodoIncompleted extends React.Component{
  render() {
    return (
      <div className="incompleted">
        <h3>To Do:</h3>
        <TodoItems {...this.props} type="incompleted" />
      </div>
    );
  }
}

class TodoCompleted extends React.Component{
  render() {
    return (
      <div className="completed">
        <h3>Done:</h3>
        <TodoItems {...this.props} type="completed" />
      </div>
    );
  }
}

class TodoItems extends React.Component{
  render() {
    var Items = this.props.items.map(function(item, i){
      return <TodoItem {...this.props} key={i} index={i} text={item} />
    }.bind(this))

    if(!this.props.items.length){
      return <div className="todo-list">暂无条目</div>
    }

    return (
      <div className="todo-list">
        <ul>
          {Items}
        </ul>
      </div>
    )
  }
}

class TodoItem extends React.Component{
  toggle(e){
    var index = this.props.index,
    type = this.props.type;

    this.props.onToggle(type, index)
  }
  del(){
    this.props.onDel(this.props.type, this.props.index);
  }
  render() {
    return (
      <li>
        <span>{this.props.index + 1}</span>
        <input type="checkbox" checked={this.props.type=='completed'} onChange={this.toggle.bind(this)} />
        <a onClick={this.del.bind(this)}>删除</a>
        <h3>{this.props.text}</h3>
      </li>
    );
  }
}


export default class Example4 extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      incompleted : [],
      completed : []
    };
  }

  add(text){
    this.state.incompleted.push(text);
    this.setState(this.state);
  }

  del(type, index){
    this.state[type].splice(index, 1);
    this.setState(this.state);
  }

  complete(index){
    var item = this.state.incompleted.splice(index, 1);
    this.state.completed.push(item);
    this.setState(this.state);
  }

  incomplete(index){
    var item = this.state.completed.splice(index, 1);
    this.state.incompleted.push(item);
    this.setState(this.state);
  }

  toggle(type, index){
    type == 'completed' ? this.incomplete(index) : this.complete(index);
  }

  render(){
    return (
      <div className="todo">
        <TodoInput onAdd={this.add.bind(this)} />
        <TodoIncompleted items={this.state.incompleted} onToggle={this.toggle.bind(this)} onDel={this.del.bind(this)}/>
        <TodoCompleted items={this.state.completed} onToggle={this.toggle.bind(this)} onDel={this.del.bind(this)}/>
      </div>
    )
  }
}